#!/usr/bin/env python
# encoding: utf-8

from app.views.api import route_api
from  flask import request,jsonify,g
import requests,json,decimal

from app import db
from app.model import User
from app.model import Electronic
from app.model import ElectronicLog

from app.common.libs.Helper import getFormatDate, getCurrentDate
from app.common.libs.UserService import UserService

from sqlalchemy import func, desc

@route_api.route("/electronicLog/fetch",methods = [ "GET","POST" ])
def electronicLogFetch():
    resp = { 'code':20000,'message':'操作成功~', 'data':{}}
    req     = request.values
    query = db.session.query( ElectronicLog, Electronic ).filter( ElectronicLog.electronic_id == Electronic.id)
    if 'status' in req:
        if req['status']:
            status  = int(req['status'])
            query = query.filter( Electronic.status == status)
    if 'type' in req:
        if req['type']:
            type  = int(req['type'])
            query = query.filter( ElectronicLog.type == type)
    if 'project' in req:
        project = req['project']
        query = query.filter( Electronic.project.like('%'+project+'%'))
    if 'name' in req:
        name = req['name']
        query = query.filter( Electronic.name.like('%'+name+'%'))
    if 'sn' in req:
        sn = req['sn']
        query = query.filter( Electronic.sn.like('%'+sn+'%'))

    page   = int( req['page'] ) if 'page' in req else 0
    limit  = int( req['limit'] ) if 'limit' in req else 0
    offset = ( page - 1 ) * limit

    total = query.count()
    data = query.order_by(desc(ElectronicLog.created_time)).offset( offset ).limit( limit ).all()

    items = [{
        'log':{
            'id':log.id,
            'type':log.type,
            'count':log.count,
            'created_time':log.created_time
        },
        'electronic':{
            'id':elec.id,
            'name':elec.name,
            'sn':elec.sn,
            'package':elec.package,
            'status':elec.status,
            'price':str(elec.price),
            'spec':elec.spec,
            'delivery':elec.delivery,
            'stock':elec.stock,
            'position':elec.position,
            'project':elec.project,
            'supplier':elec.supplier
        }
    } for log, elec in data]

    resp['data']['items'] = items
    resp['data']['total'] = total

    return jsonify( resp )

